package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.mapper.UserInfoMapper;
import com.book.pojo.UserInfo;
import com.book.service.UserInfoService;
import com.book.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {


    @Override
    public String login(String username, String userPassword) {
        UserInfo userInfo = findByUserNameAndUserPassword(username,userPassword);
        if (null == userInfo) {
            return "account / password Error";
        }
        return "Login Success";
    }

    public UserInfo findByUserNameAndUserPassword(String username, String userPassword) {
        return getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername,username).eq(UserInfo::getUserPassword,userPassword));
    }

    @Override
    public String register(UserInfo userInfo) {
        if(checkUserExists(userInfo.getUsername())){
            throw new RuntimeException("用户名已存在");
        }
        userInfo.setCreateDate(new Date());
        save(userInfo);
        return "Register Success";
    }

     public boolean checkUserExists(String username) {
        return count(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername,username) ) > 0;
    }
}